package com.hdoit.pisces.web.other.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.ModelAndView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hdoit.pisces.logical.rel.model.Event;
import com.hdoit.pisces.logical.rel.model.Relationship;
import com.hdoit.pisces.logical.rel.model.Relative;
import com.hdoit.pisces.logical.rel.service.IEventService;
import com.hdoit.pisces.logical.rel.service.IRelationshipService;
import com.hdoit.pisces.logical.rel.service.IRelativeService;
import com.hdoit.pisces.logical.viewmodel.RelationshipSearch;
import com.tennetcn.common.logical.superbase.service.IRoleEmployeeService;
import com.tennetcn.common.logical.superbase.service.IRoleService;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.web.cbase.AuthPassport;

@Controller
@RequestMapping(value = "/admin/")
public class HistoryController extends BaseController {

	@Override
	public String getRoutePath() {
		return "areas/admin/";
	}

	private IRelationshipService relationshipService;

	public IRelationshipService getRelationshipService() {
		return relationshipService;
	}

	@Resource
	public void setRelationshipService(IRelationshipService relationshipService) {
		this.relationshipService = relationshipService;
	}

	private IRelativeService relativeService;

	public IRelativeService getRelativeService() {
		return relativeService;
	}

	@Resource
	public void setRelativeService(IRelativeService relativeService) {
		this.relativeService = relativeService;
	}

	private IEventService eventService;

	public IEventService getEventService() {
		return eventService;
	}

	@Resource
	public void setEventService(IEventService eventService) {
		this.eventService = eventService;
	}

	private IRoleEmployeeService roleEmployeeService;

	public IRoleEmployeeService getRoleEmployeeService() {
		return roleEmployeeService;
	}

	@Resource
	public void setRoleEmployeeService(IRoleEmployeeService roleEmployeeService) {
		this.roleEmployeeService = roleEmployeeService;
	}

	private IRoleService roleService;

	public IRoleService getRoleService() {
		return roleService;
	}

	@Resource
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	private final String historyViewName = "xln";
	private final String uploadViewName = "uploadIcon";
	private final String doUploadViewName = "doUpload";
	private Relative relative;
	private List<Event> events;
	private List<Relative> relatives;
	private String path;
	private List<String> picPaths;
	private List<String> vidPaths;
	private String iconPath;
	private String qrcodePath;
	private String iconName;

	@RequestMapping(value = historyViewName, method = { RequestMethod.GET,
			RequestMethod.POST })
	@AuthPassport
	public String index(Model model, String num, RelationshipSearch search,
			HttpServletRequest request, HttpServletResponse response) {
		relatives = relativeService.queryList();
		relative = relativeService.queryModel(num);
		events = eventService.queryList();
		String key = null;
		System.out.println(relationshipService.queryList().size()
				+ "7454178415784");
		List<Relationship> relationship = relationshipService.queryList();
		int size = relationship.size();
		System.out.println(size + "7985446461");
		for (int i = relationship.size() - 1; i >= 0; i--) {
			if (!relationship.get(i).getRelativeId().equals(num)) {
				relationship.remove(i);
			}
		}
		String id = null;
		List<String> roleId = null;
		String mark = null;
		if (getLoginModel() == null) {
			id = null;
		} else {
			id = getLoginModel().getLoginId();
			roleId = roleEmployeeService.queryRoleIdsByEmployeeId(id);
			mark = roleService.queryModel(roleId.get(0)).getRoleMark();
		}

		if (id != null) {
			if (relationship.get(0).getEmployeeId()
					.equals(getLoginModel().getLoginId())) {
				key = "true";

			} else if (mark.equals("2") || mark.equals("1")) {
				key = "true";
			} else {

				key = "false";
			}
		} else {

			key = "false";
		}

		int k = events.size();

		for (int i = events.size() - 1; i >= 0; i--) {
			if (!relative.getRelativeId().equals(events.get(i).getRelativeId())) {
				events.remove(i);
			}

		}

		if (events.size() > 1) {
			for (int i = 0; i < events.size() - 1; i++) {
				for (int j = 0; j < events.size() - 1 - i; j++) {
					if (events.get(j).getEventDate() != null && events.get(j + 1).getEventDate() != null) {
						if (events.get(j).getEventDate()
								.compareTo(events.get(j + 1).getEventDate()) > 0) {
							events.add(j + 2, events.get(j));
							events.remove(j);
						}
					}
				}
			}
		}

		// 图片路径
		path = "/opt/apache-tomcat-7.0.79/webapps/resources/"
				+ relative.getRelativeId() + "/images";
		File folder = new File(path);
		if (!folder.exists())
			folder.mkdirs();
		File temp[] = folder.listFiles();
		picPaths = new ArrayList();
		for (int i = 0; i < temp.length; i++) {
			picPaths.add("http://119.29.26.204:8080/resources/"
					+ relative.getRelativeId() + "/images/" + temp[i].getName());
		}

		// 视频路径
		path = "/opt/apache-tomcat-7.0.79/webapps/resources/"
				+ relative.getRelativeId() + "/videos";
		File folder1 = new File(path);
		if (!folder1.exists())
			folder1.mkdirs();
		File temp1[] = folder1.listFiles();
		vidPaths = new ArrayList();
		for (int i = 0; i < temp1.length; i++) {
			vidPaths.add("http://119.29.26.204:8080/resources/"
					+ relative.getRelativeId() + "/videos/"
					+ temp1[i].getName());
		}

		// 头像路径
		iconName = num;
		String iconCatalog = "/opt/apache-tomcat-7.0.79/webapps/resources/"
				+ num + "/" + num + ".png";
		File file = new File(iconCatalog);
		if (!file.exists())
			iconPath = "http://119.29.26.204:8080/resources/person.png";
		else
			iconPath = "http://119.29.26.204:8080/resources/" + num + "/" + num
					+ ".png";

		// 二维码路径
		String qrcodeCatalog = "/opt/apache-tomcat-7.0.79/webapps/resources/"
				+ num + "/qrcode.png";
		String content = "http://119.29.26.204:8080/pisces/admin/xln?num="
				+ num;
		file = new File(qrcodeCatalog);
		if (!file.exists()) {
			Hashtable<EncodeHintType, Object> hts = new Hashtable<EncodeHintType, Object>();
			hts.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 纠错等级
			hts.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定编码格式为UTF-8
			try {

				BitMatrix bitMatrix = new MultiFormatWriter().encode(content, // 编码内容,编码类型(这里指定为二维码),
						BarcodeFormat.QR_CODE, 300, 300, hts); // 图片宽度,图片高度,设置参数

				MatrixToImageWriter.writeToFile(bitMatrix, "png", file); // 生成的二维码图片

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		qrcodePath = "http://119.29.26.204:8080/resources/" + num
				+ "/qrcode.png";
		model.addAttribute("qrcodePath", qrcodePath);
		model.addAttribute("iconPath", iconPath);
		model.addAttribute("vidPaths", vidPaths);
		model.addAttribute("picPaths", picPaths);
		model.addAttribute("key", key);
		model.addAttribute("relative", relative);
		model.addAttribute("events", events);
		return view(historyViewName);
	}

	@RequestMapping(value = uploadViewName, method = { RequestMethod.GET,
			RequestMethod.POST })
	public String index() {
		return view(uploadViewName);
	}

	@RequestMapping(value = doUploadViewName, method = RequestMethod.POST)
	@AuthPassport
	public ModelAndView uploadFileHandler(HttpServletRequest request,
			Model model, @RequestParam("file") MultipartFile[] files) {

		// Root Directory.
		String uploadRootPath = "/opt/apache-tomcat-7.0.79/webapps/resources/"
				+ relative.getRelativeId();

		File uploadRootDir = new File(uploadRootPath);

		// Create directory if it not exists.
		if (!uploadRootDir.exists()) {
			;
			uploadRootDir.mkdirs();
		}

		List<File> uploadedFiles = new ArrayList<File>();
		for (int i = 0; i < files.length; i++) {

			MultipartFile file = files[i];

			// Client File Name
			String name = iconName + ".png";

			if (name != null && name.length() > 0) {
				try {
					byte[] bytes = file.getBytes();

					// Create the file on server
					File serverFile = new File(uploadRootDir.getAbsolutePath()
							+ File.separator + name);

					// Stream to write data to file in server.
					BufferedOutputStream stream = new BufferedOutputStream(
							new FileOutputStream(serverFile));
					stream.write(bytes);
					stream.close();

					uploadedFiles.add(serverFile);

				} catch (Exception e) {
					System.out.println("Error Write file: " + name);
				}
			}
		}

		model.addAttribute("qrcodePath", qrcodePath);
		model.addAttribute("iconPath", iconPath);
		model.addAttribute("vidPaths", vidPaths);
		model.addAttribute("picPaths", picPaths);
		model.addAttribute("relative", relative);
		model.addAttribute("events", events);
		return new ModelAndView("redirect:/admin/xln?num="
				+ relative.getRelativeId());

	}

}
